package com.gzdh.tang.modu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzdh.tang.comm.util.ObjectUtil;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.config.youxin.YouXinRequest;
import com.gzdh.tang.dishrecognition.dto.DiningTableListDto;
import com.gzdh.tang.dishrecognition.dto.ReserveListDto;
import com.gzdh.tang.mobile.entity.Bmcm;
import com.gzdh.tang.mobile.service.BmcmService;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.mapper.ReserveMapper;
import com.gzdh.tang.modu.model.FoodBean;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.modu.util.DateUtil;
import com.gzdh.tang.modu.vo.InStockTempVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

@DS("card")
@Slf4j
@Service("reserveService")
public class ReserveServiceImpl extends ServiceImpl<ReserveMapper, Reserve> implements ReserveService {


    @Autowired
    FkService fkService;

    @Autowired
    GsService gsService;

    @Autowired
    MacMainpSbruanService macMainpSbruanService;

    @Autowired
    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    @Autowired
    MacMainpSbruanKlService macMainpSbruanKlService;


    @Autowired
    ReserveMapper reserveMapper;

    @Autowired
    BmcmService bmcmService;

    @Autowired
    MacMainpOrderService macMainpOrderService;

    @Autowired
    MacMainpSbruanKlDinnerService macMainpSbruanKlDinnerService;


    /**
     * 默认刷卡支付
     *
     * @param deviceId
     * @param price
     * @param reqSeqNo
     * @throws RuntimeException
     */
    @Override
    public String toCardPay(String deviceId, int price, Fk fk, String reqSeqNo, List<FoodBean> foodBeanList) throws RuntimeException {
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
//        Fk fk = null;
//        log.info("【" + deviceId + "】查询的cardsn：" + cardsn);
        if (price == 0) {
            throw new RuntimeException("金额异常，请重新输入");
        }
//        List<Fk> fkList = fkService.list(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
//        if (fkList.size() > 1) {
//            log.info("【" + deviceId + "】" + fkList.toString());
//            throw new RuntimeException("刷卡失败：请联系管理员：#101");
//        } else if (fkList.size() > 0) {
//            fk = fkList.get(0);
//        } else {
//            throw new RuntimeException("非法卡");
//        }
        long count = gsService.count(new QueryWrapper<Gs>().lambda().eq(Gs::getKh, fk.getKh()).eq(Gs::getCardno, fk.getCardno()));
        if (count > 0) {
            throw new RuntimeException("此卡已挂失,请回收");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService.list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId, macMainpSbruan.getId()));
        if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
            throw new RuntimeException("不支持此卡类");
        }
        String sc = "0";
        BigDecimal cardPrice = new BigDecimal(0);
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        if (btye.compareTo(xfPrice) >= 0) {
            sc = "1";
            cardPrice = btye;
        } else if (kye.compareTo(xfPrice) >= 0) {
            sc = "0";
            cardPrice = kye;
        } else {
            throw new RuntimeException("余额不足");
        }
        long counts = this.count(new QueryWrapper<Reserve>().lambda().eq(Reserve::getLsh2, String.valueOf(reqSeqNo)).eq(Reserve::getPosnum, macMainpSbruan.getPos()));
        if (counts == 0) {
            if(foodBeanList.size() == 0) {
                FoodBean foodBean = new FoodBean();
                foodBean.setFoodName("现金菜");
                foodBean.setNumber(1);
                foodBean.setPrice(new BigDecimal(price).divide(new BigDecimal(100)).toPlainString());
                foodBeanList.add(foodBean);
            }
            for (FoodBean foodBean : foodBeanList) {
                int divideMoney = ObjectUtil.getBigDecimal(foodBean.getPrice()).multiply(new BigDecimal(100)).intValue();
                insertReserve(deviceId, String.valueOf(reqSeqNo), divideMoney, foodBean.getNumber(), fk, macMainpSbruan, foodBean.getFoodName(), macMainpSbruan.getCode(), cardPrice, sc, String.valueOf(reqSeqNo), new Date());
                cardPrice = cardPrice.subtract(ObjectUtil.getBigDecimal(foodBean.getPrice()));
            }
        }
        return sc;
    }

    @Override
    public Fk toCardPay2(String deviceId, int price, Fk fk, String reqSeqNo, int type, Date date) throws RuntimeException {
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
        BigDecimal xfPrice2 = new BigDecimal(price).divide(new BigDecimal(100));
        if (type <= 0) {
            if (xfPrice.compareTo(new BigDecimal(fk.getKye()).add(new BigDecimal(fk.getBtye()))) > 0) {
                throw new RuntimeException("余额不足");
            }
            long count = gsService.count(new QueryWrapper<Gs>().lambda().eq(Gs::getKh, fk.getKh()).eq(Gs::getCardno, fk.getCardno()));
            if (count > 0) {
                throw new RuntimeException("此卡已挂失,请回收");
            }
        }
        if (price == 0) {
            throw new RuntimeException("金额异常，请重新输入");
        }

        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService.list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId, macMainpSbruan.getId()));
        if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
            throw new RuntimeException("不支持此卡类");
        }
        String sc = "0";
        BigDecimal cardPrice = xfPrice;
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        if (btye.compareTo(new BigDecimal(0)) > 0) {
            sc = "1";
            cardPrice = btye;
            if (btye.compareTo(xfPrice) <= 0) {
                xfPrice = btye;
                fk.setBtye("0");
            } else {
                fk.setBtye(btye.subtract(xfPrice).toPlainString());
            }
        } else {
            cardPrice = kye;
            fk.setKye(kye.subtract(xfPrice).toPlainString());
        }
        long counts = this.count(new QueryWrapper<Reserve>().lambda().eq(Reserve::getLsh2, String.valueOf(reqSeqNo)).eq(Reserve::getPosnum, macMainpSbruan.getPos()));
        if (counts == 0) {
            insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(), cardPrice, sc, String.valueOf(reqSeqNo), date);
        }
        xfPrice = xfPrice2.subtract(xfPrice);
        if ("1".equals(sc) && xfPrice.compareTo(new BigDecimal(0)) > 0) {
            sc = "0";
            cardPrice = kye;
            date = new Date(date.getTime() + 100);
            //上一笔扣补贴，并存在没扣完;
            counts = this.count(new QueryWrapper<Reserve>().lambda().eq(Reserve::getLsh2, String.valueOf(reqSeqNo) + "N").eq(Reserve::getPosnum, macMainpSbruan.getPos()));
            if (counts == 0) {
                insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(), 1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(), cardPrice, sc, String.valueOf(reqSeqNo), date);
            }
            fk.setKye(kye.subtract(xfPrice).toPlainString());
        }
        return fk;
    }

    @Override
    public Fk toPayByYouXin(String deviceId, int price, Fk fk, String reqSeqNo, int type, Date date) throws RuntimeException {
        if (price == 0) {
            throw new RuntimeException("金额异常，请重新输入");
        }
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100), 2, RoundingMode.DOWN);
        YouXinRequest youXinRequest = new YouXinRequest();
        String phone = fk.getId() != null ? fk.getId().trim() : "";
        Map<String, Object> resMap = youXinRequest.getBalanceByPhone(phone);
        if(resMap == null) {
            throw new RuntimeException("获取余额异常");
        }
        BigDecimal balance = resMap.get("balance") != null ? new BigDecimal(resMap.get("balance").toString()) : new BigDecimal(0);
        if (type <= 0) {
            if (xfPrice.compareTo(balance) > 0) {
                throw new RuntimeException("余额不足");
            }
            long count = gsService.count(new QueryWrapper<Gs>().lambda().eq(Gs::getKh, fk.getKh()).eq(Gs::getCardno, fk.getCardno()));
            if (count > 0) {
                throw new RuntimeException("此卡已挂失,请回收");
            }
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService.list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId, macMainpSbruan.getId()));
        if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
            throw new RuntimeException("不支持此卡类");
        }
        Map<String, Object> map = bmcmService.getMap(new QueryWrapper<Bmcm>().select("dinnerTime").eq("bm", macMainpSbruan.getDinner()));
        String dinnerTime = (map != null && map.get("dinnerTime") != null) ? map.get("dinnerTime").toString() : "";
        String orderAmount = xfPrice.setScale(2, BigDecimal.ROUND_DOWN).toPlainString();
        Map<String, Object> payResMap = youXinRequest.orderPay(reqSeqNo, orderAmount, dinnerTime, phone);
        if(payResMap == null) {
            throw new RuntimeException("支付失败");
        }
        if(!String.valueOf(payResMap.get("result")).equals("1")) {
            throw new RuntimeException(String.valueOf(payResMap.get("message")).trim());
        }
        String sc = "0";
        long counts = this.count(new QueryWrapper<Reserve>().lambda().eq(Reserve::getLsh2, String.valueOf(reqSeqNo)).eq(Reserve::getPosnum, macMainpSbruan.getPos()));
        if (counts == 0) {
            insertReserve(deviceId, String.valueOf(reqSeqNo), xfPrice.multiply(new BigDecimal(100)).intValue(), 1, fk,
                    macMainpSbruan, "现金菜", macMainpSbruan.getCode(), balance, sc, String.valueOf(reqSeqNo), date);
        }
        String nowStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        String outTradeNo = "YXTK" + macMainpSbruan.getPos() + nowStr;
        Map<String, Object> refundMap = youXinRequest.orderRefund(reqSeqNo, "0.1", phone, "用户自主退餐");
        return fk;
    }

    /**
     * 通过cardno刷卡支付
     *
     * @param deviceId
     * @param price
     * @param cardno
     * @param reqSeqNo
     * @throws RuntimeException
     */
    @Override
    public void toPayByCardNo(String deviceId, int price, String cardno, String reqSeqNo, int orderCount) throws RuntimeException {
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, cardno));
        if (fk == null) {
            throw new RuntimeException("查无此人");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService
                .getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService
                .list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId, macMainpSbruan.getId()));
        if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
            throw new RuntimeException("不支持此卡类");
        }
        String sc = "0";
        BigDecimal cardPrice = new BigDecimal(0);
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        if (btye.compareTo(xfPrice) >= 0) {
            sc = "1";
            cardPrice = btye;
        } else if (kye.compareTo(xfPrice) >= 0) {
            sc = "0";
            cardPrice = kye;
        } else {
            throw new RuntimeException("余额不足");
        }
        long counts = this.count(new QueryWrapper<Reserve>().lambda()
                .eq(Reserve::getLsh2, String.valueOf(reqSeqNo)).eq(Reserve::getPosnum, macMainpSbruan.getPos()));
        if (counts == 0) {
            if (!insertReserve(deviceId, String.valueOf(reqSeqNo), price, 1,
                    fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(), cardPrice, sc, String.valueOf(reqSeqNo), new Date(), orderCount)
            ) {
                throw new RuntimeException("余额不足");
            }
        }

    }

    @Override
    public void toPayByAli(String device, int price, String cardno, String reqSeqNo) throws RuntimeException {

    }

    /**
     * 通过微信支付，直接插入记录，
     *
     * @param deviceId
     * @param price
     * @param reqSeqNo
     * @return
     * @throws RuntimeException
     */
    @Override
    public String toPayByWeixin(String deviceId, int price, String reqSeqNo) throws RuntimeException {
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, macMainpSbruan.getCardno()));
        if (fk == null) {
            throw new RuntimeException("系统参数未设置");
        }
        long counts = this.count(new QueryWrapper<Reserve>().lambda().eq(Reserve::getLsh2, String.valueOf(reqSeqNo)).eq(Reserve::getPosnum, macMainpSbruan.getPos()));
        if (counts == 0) {
            if (!insertReserve(deviceId, String.valueOf(reqSeqNo), price, 1, fk, macMainpSbruan, "现金菜", macMainpSbruan.getCode(), new BigDecimal(price).divide(new BigDecimal(100)), "3", String.valueOf(reqSeqNo), new Date())) {
                throw new RuntimeException("余额不足");
            }
        }
        return macMainpSbruan.getCardno();

    }

    @Override
    public boolean insertReserve(String rgTermSN, String reqSeqNo, int price, int sl, Fk fk, MacMainpSbruan macMainpSbruan, String hName, String code, BigDecimal cardPrice, String sc, String orders, Date date) throws RuntimeException {
        return insertReserve(rgTermSN, reqSeqNo, price, sl, fk, macMainpSbruan, hName, code, cardPrice, sc, orders, date, 0);
    }

    @Override
    public boolean insertReserve(String rgTermSN, String reqSeqNo, int price, int sl, Fk fk, MacMainpSbruan macMainpSbruan,
                                 String hName, String code, BigDecimal cardPrice, String sc, String orders, Date date, int orderCount) throws RuntimeException {
        BigDecimal xfPrice = new BigDecimal(price).divide(new BigDecimal(100));
        BigDecimal yePrice = new BigDecimal(0);
        String je = (new BigDecimal(price).multiply(new BigDecimal(sl))).divide(new BigDecimal(100)).toPlainString();

        yePrice = cardPrice.subtract(xfPrice);
        Reserve reserve = new Reserve();
        reserve.setZkl("100");
        reserve.setCardno(fk.getCardno());
        reserve.setZl(macMainpSbruan.getZl());
        reserve.setBqh(macMainpSbruan.getBqh());
        reserve.setKsh(macMainpSbruan.getKsh());
        reserve.setBed("0");
        reserve.setPosnum(macMainpSbruan.getPos());
        reserve.setDinner(macMainpSbruan.getDinner());
        reserve.setCode(code);
        reserve.setSl(sl);
        reserve.setStatus("1");
        reserve.setJe(je);
        reserve.setOriginalAmount(je);
        reserve.setDiscountAmount("0");
        try {
            reserve.setYe(yePrice.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
        } catch (Exception e) {
            log.error("余额错误");
            reserve.setYe("0");
        }
        reserve.setKl(fk.getKl());
        reserve.setSc(sc);
        reserve.setLsh2(String.valueOf(reqSeqNo));
        reserve.setCzrq(date);
        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        reserve.setHname(hName);
        reserve.setSddz(rgTermSN);
        reserve.setCs(0);
        reserve.setOpenid(fk.getCardsn());
        reserve.setKehu(fk.getName());
        reserve.setZfserialnumber(orders);
        reserve.setAddr(macMainpSbruan.getAddr());
        reserve.setOrderCount(orderCount);
        this.save(reserve);
        return true;
    }


    private String getDinner(MacMainpSbruan macMainpSbruan) throws Exception {
        String hourMin = new SimpleDateFormat("HH:mm").format(new Date());
        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService.list(new QueryWrapper<MacMainpSbruanDinner>().lambda().eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
            if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                return goo.getDinner();
            }
        }
        throw new Exception("未找到该餐次");
    }

    private boolean judeKl(List<MacMainpSbruanKl> macMainpSbruanKlList, String kl) {
        for (MacMainpSbruanKl goo : macMainpSbruanKlList) {
            if (goo.getKl().equals(kl.trim())) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void depotCardPay(TangDevice tangDevice, List<InStockTempVo> inStockTempVo, Fk fk, String orders, String sc, String fl) {
        int i = 0;
        Date date = new Date();
        for (InStockTempVo goo : inStockTempVo) {
            i++;
            Reserve reserve = new Reserve();
            reserve.setCardno(fk.getCardno());
            reserve.setZl(tangDevice.getZl());
            reserve.setBqh(tangDevice.getBqh());
            reserve.setKsh(tangDevice.getKsh());
            reserve.setBed("0");
            reserve.setPosnum(tangDevice.getPosnum());
            reserve.setDinner(tangDevice.getDinner());
            reserve.setCode(tangDevice.getCode());
            reserve.setSl(goo.getNumber().intValue());
            reserve.setJe(goo.getNumber().multiply(new BigDecimal(goo.getSalePrice())).stripTrailingZeros().toPlainString());
            reserve.setYe("0");
            reserve.setKl(fk.getKl());
            reserve.setSc(sc);
            reserve.setLsh2(orders);
            reserve.setCzrq(new Date(date.getTime() + (i * 10)));
            reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
            reserve.setHname(goo.getDevicename());
            reserve.setSddz(orders);
            reserve.setCs(0);
            reserve.setTmpFieldZk(fl);
            reserve.setKehu("");
            reserve.setStatus("1");
            reserve.setSctime("");
            reserve.setZfserialnumber(orders);
            reserve.setAddr(tangDevice.getAddr());
            this.save(reserve);
        }
    }


    @Override
    public int payCounts(String cardno, String dinner) {
        return reserveMapper.payCounts(cardno, dinner).size();
    }


    @Override
    public List<ReserveListDto> getOrderList(String startTime, String endTime, String deviceId) {
        return reserveMapper.getReserve(startTime + " 00:00:00", endTime + " 23:59:59", deviceId);
    }

    @Override
    public List<DiningTableListDto> getDiningTableList(Integer type, String startTime, String endTime, String bqh, String ksh) {
        List<Map<String, Object>> list;
        if(type == 0) {
            list = reserveMapper.getDiningTableList(startTime + " 00:00:00", endTime + " 23:59:59", bqh, ksh);
        } else if (type == 1) {
            list = reserveMapper.getCleanedDiningTableList(startTime + " 00:00:00", endTime + " 23:59:59", bqh, ksh);
        } else {
            list = new LinkedList<>();
        }
        List<DiningTableListDto> finalList = new LinkedList<>();
        for (Map<String, Object> map : list) {
            DiningTableListDto dto = new DiningTableListDto();
            dto.setCardNo(ObjectUtil.getStr(map.get("cardno")));
            dto.setId(ObjectUtil.getStr(map.get("id")));
            dto.setBqh(ObjectUtil.getStr(map.get("bqbm")));
            dto.setBqName(ObjectUtil.getStr(map.get("bqname")));
            dto.setKsh(ObjectUtil.getStr(map.get("ksbm")));
            dto.setKsName(ObjectUtil.getStr(map.get("ksname")));
            dto.setDiningTime(ObjectUtil.getStr(map.get("dingsj")));
            dto.setDate(ObjectUtil.getStr(map.get("DCRQ")));
            dto.setDinner(ObjectUtil.getStr(map.get("dinner")));
            dto.setTotalCost(ObjectUtil.getStr(map.get("zje")));
            dto.setPrice(ObjectUtil.getStr(map.get("chaweifee")));
            dto.setNumber(ObjectUtil.getStr(map.get("chawei")));
            dto.setUseTimes(ObjectUtil.getStr(map.get("str1")));
            finalList.add(dto);
        }
        return finalList;
    }

    @Override
    public List<Reserve> getDiningTableDetails(String ksh, String dinner, String date, String useTimes) {
        if("0".equals(useTimes)) {
            return reserveMapper.getDiningTableDetails(ksh, dinner, date);
        } else {
            return reserveMapper.getCleanedTableDetails(ksh, dinner, date, useTimes);
        }
    }

    @Override
    public String getMaxUseTimes(Map<String, Object> params) {
        return reserveMapper.getMaxUseTimes(params);
    }

    @Override
    public Integer updateUseTimes(Map<String, Object> params) {
        return reserveMapper.updateUseTimes(params);
    }

    @Override
    @Transactional
    public String drRefundProduct(String orders) throws RuntimeException {
        List<Reserve> reserveList = this.list(new QueryWrapper<Reserve>().lambda().eq(Reserve::getCs, 0).eq(Reserve::getZfserialnumber, orders));
        if (reserveList.size() == 0) {
            throw new RuntimeException("该订单已退，请刷新后操作");
        }
        String tkOrders = dealWithRefund(reserveList, orders);
        String sc = reserveList.get(0).getSc();
        if ("3".equals(sc)) {
            //插入微信临时表
            MacMainpOrder macMainpOrder = macMainpOrderService.getOne(new QueryWrapper<MacMainpOrder>().lambda().eq(MacMainpOrder::getOrders, orders).eq(MacMainpOrder::getOrderType, 0));
            macMainpOrder.setOrderType(1);
            macMainpOrder.setId(null);
            macMainpOrder.setRefundOrder(tkOrders);
            macMainpOrderService.save(macMainpOrder);
        } else if ("4".equals(sc)) {
            MacMainpOrder macMainpOrder = macMainpOrderService.getOne(new QueryWrapper<MacMainpOrder>().lambda().eq(MacMainpOrder::getOrders, orders).eq(MacMainpOrder::getOrderType, 0));
            macMainpOrder.setOrderType(2);
            macMainpOrder.setId(null);
            macMainpOrder.setRefundOrder(tkOrders);
            macMainpOrderService.save(macMainpOrder);
        } else if("9".equals(sc)) {
            MacMainpOrder macMainpOrder = macMainpOrderService.getOne(new QueryWrapper<MacMainpOrder>().lambda().eq(MacMainpOrder::getOrders, orders).eq(MacMainpOrder::getOrderType, 0));
            macMainpOrder.setOrderType(3);
            macMainpOrder.setId(null);
            macMainpOrder.setRefundOrder(tkOrders);
            macMainpOrderService.save(macMainpOrder);
        }
        return tkOrders;
    }

    @Override
    public String priceReserve(String cardno, String dinner) {

        return reserveMapper.getPriceByReserve(cardno, new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()), dinner);
    }

    @Override
    public Map<String, String> hexiaoReserve(int cardno, String dinner) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, String> resMap = new HashMap<>();
        resMap.put("code", "0");
        log.info("查询卡号：" + cardno + "/餐次：" + dinner + "/就餐时间：" + sdf.format(new Date()));
        List<Map<String, Object>> reserveList = reserveMapper.countReserves(cardno, dinner, sdf.format(new Date()) + " 00:00:00", 0);

        if (!reserveList.isEmpty()) {
            //存在订餐，按订餐处理，更改打印标志，返回成功核销消费
            reserveMapper.updateStatus(cardno, dinner, sdf.format(new Date()) + " 00:00:00");
            resMap.put("code", "1");
            //相当于返回核销成功
            return resMap;
        }
        //不存在消费，判断是否属于第一次消费，如果属于第一次消费，则按第一次消费价格进行消费，如果非第一次消费，则按后面价格消费
        reserveList = reserveMapper.countReserves(cardno, dinner, sdf.format(new Date()), 1);
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, cardno));
        resMap.put("reserveSize", String.valueOf(reserveList.size()));
        MacMainpSbruanKlDinner macMainpSbruanKlDinner;
//        if (!reserveList.isEmpty()) {
//            //存在消费，按第二次消费价格消费，
//            macMainpSbruanKlDinner = macMainpSbruanKlDinnerService
//                    .getOne(new QueryWrapper<MacMainpSbruanKlDinner>().lambda()
//                            .eq(MacMainpSbruanKlDinner::getKl, fk.getKl())
//                            .eq(MacMainpSbruanKlDinner::getDinner, dinner).eq(MacMainpSbruanKlDinner::getCounts, 2));
//        } else {
//            //按第一次价格消费
//            macMainpSbruanKlDinner = macMainpSbruanKlDinnerService
//                    .getOne(new QueryWrapper<MacMainpSbruanKlDinner>().lambda()
//                            .eq(MacMainpSbruanKlDinner::getKl, fk.getKl())
//                            .eq(MacMainpSbruanKlDinner::getDinner, dinner).eq(MacMainpSbruanKlDinner::getCounts, 1));
//
//        }
        if (!reserveList.isEmpty()) {
            macMainpSbruanKlDinner = macMainpSbruanKlDinnerService
                    .getOne(new QueryWrapper<MacMainpSbruanKlDinner>().lambda()
                            .eq(MacMainpSbruanKlDinner::getKl, fk.getKl())
                            .eq(MacMainpSbruanKlDinner::getDinner, dinner).eq(MacMainpSbruanKlDinner::getCounts, reserveList.size() + 1));
        } else {
            //按第一次价格消费
            macMainpSbruanKlDinner = macMainpSbruanKlDinnerService
                    .getOne(new QueryWrapper<MacMainpSbruanKlDinner>().lambda()
                            .eq(MacMainpSbruanKlDinner::getKl, fk.getKl())
                            .eq(MacMainpSbruanKlDinner::getDinner, dinner).eq(MacMainpSbruanKlDinner::getCounts, 1));
        }



        if (macMainpSbruanKlDinner == null) {
            macMainpSbruanKlDinner = macMainpSbruanKlDinnerService
                    .getOne(new QueryWrapper<MacMainpSbruanKlDinner>().lambda()
                            .eq(MacMainpSbruanKlDinner::getKl, fk.getKl())
                            .eq(MacMainpSbruanKlDinner::getDinner, dinner).eq(MacMainpSbruanKlDinner::getCounts, 0));
        }


        if (macMainpSbruanKlDinner == null) {
            resMap.put("code", "-1");
            resMap.put("msg", "【" + (reserveList.size() + 1) + "】该次数价格尚未设置");
            return resMap;
        }
        if (new BigDecimal(macMainpSbruanKlDinner.getPrice()).compareTo(new BigDecimal(fk.getKye())) > 0) {
            //当消费金额，大于发卡表余额，应该提示卡余额不足
            resMap.put("code", "-2");
            resMap.put("msg", "余额不足");
            return resMap;
        }
        resMap.put("payPrice", macMainpSbruanKlDinner.getPrice());
        return resMap;
    }

    @Override
    @Transactional
    public void toRollback(String reqSeqNo) throws RuntimeException {
        List<Reserve> reserveList = this.list(new QueryWrapper<Reserve>().lambda().eq(Reserve::getCs, 0).eq(Reserve::getLsh2, reqSeqNo));
        if (reserveList.size() == 0) {
            throw new RuntimeException("该订单已退，请刷新后操作");
        }
        String orders = reserveList.get(0).getZfserialnumber();
        String tkOrders = dealWithRefund(reserveList, orders);
        MacMainpOrder macMainpOrder = macMainpOrderService.getOne(new QueryWrapper<MacMainpOrder>().lambda().eq(MacMainpOrder::getOrders, orders).eq(MacMainpOrder::getOrderType, 0));
        if(macMainpOrder == null) {
            return;
        }
        macMainpOrder.setId(null);
        macMainpOrder.setRefundOrder(tkOrders);
        String sc = reserveList.get(0).getSc();
        switch (sc) {
            case "3":
                macMainpOrder.setOrderType(1);
                macMainpOrderService.save(macMainpOrder);
                break;
            case "4":
                macMainpOrder.setOrderType(2);
                macMainpOrderService.save(macMainpOrder);
                break;
            case "9":
                macMainpOrder.setOrderType(3);
                macMainpOrderService.save(macMainpOrder);
                break;
        }
    }

    private String dealWithRefund(List<Reserve> reserveList, String orders) {
        int i = 0;
        Date date = new Date();
        String tkOrders = orders.replace("ZF", "TK");
        for (Reserve goo : reserveList) {
            goo.setJe(new BigDecimal(goo.getJe()).multiply(new BigDecimal(-1)).toPlainString());//改为负金额
            goo.setCs(1);
            goo.setOutRefundNo(tkOrders);
            goo.setDcrq(goo.getDcrq().replace(".000", ".127"));
            goo.setCzrq(new Date(date.getTime() + (i++) * 100L));
        }
        this.saveBatch(reserveList);//保存
        reserveMapper.updateRESERV(orders);
        reserveMapper.updateRESERVEXfj(orders);
        return tkOrders;
    }
}
